import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Modal, Table, Space, Button, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import _ from 'loadsh'
import style from './ServiceAddress.module.less'
import Detail from './ServiceAddress/Detail'
import { decomporessListLicenseAndMobileAndBank } from '@src/assets/js/tool'
const { confirm } = Modal
// 获取表单字段配置
function getColumns () {
  return [
    {
      title: '收件人',
      dataIndex: 'contract',
      key: 'contract',
      render: (v, l) => {
        return v || l.structure
      }
    },
    {
      title: '收件人类型',
      dataIndex: 'action_subject',
      key: 'action_subject'
    },
    {
      title: '地址类型',
      dataIndex: 'type',
      key: 'type'
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address'
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: '操作',
      dataIndex: 'other',
      key: 'other',
      render: (v, l) => {
        if (!this.props.editable) {
          return false
        }
        return (
          <Space>
            <span
              className={style.btn} onClick={() => {
                this.setState({ modelVisible: true, modelData: _.cloneDeep(l) })
              }}
            >编辑
            </span>
            <span
              className={style.btn} onClick={() => {
                this.delConfirm(_.cloneDeep(l))
              }}
            >删除
            </span>
          </Space>
        )
      }
    }
  ]
}

class ServiceAddress extends Component {
  state = {
    currentId: '',
    dataSource: [],
    loading: false,
    modelVisible: false,
    modelData: null,
    dictionaries: {},
    arbitrators: []
  }

  // 获取案件仲裁员列表
  getArbitrators () {
    this.$get(`/api/xapc/case/${this.props.caseDetail.id}/arbitrator`)
      .then(res => {
        if (res.status === 1) {
          decomporessListLicenseAndMobileAndBank(res.data)
          this.setState({
            arbitrators: res.data
          })
        } else {
          message.warning(res.message)
        }
      })
  }

  // 获取枚举的字典值
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '送达地址类型,仲裁地位'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 获取地址数据
  getTableData () {
    this.setState({
      loading: true
    })
    this.$get('/api/xapc/deliveraddress', {
      caseid: this.props.caseDetail.id
    }).then(res => {
      this.setState({
        loading: false
      })
      if (res.status === 1) {
        this.setState({
          dataSource: res.data.map(li => {
            li.key = li.id
            return li
          })
        })
      } else {
        message.warning(res.status)
      }
    }).catch(() => {
      this.setState({
        loading: false
      })
    })
  }

  // 新增地址请求
  addRequest (d) {
    const hide = message.loading('新增地址中', 120)
    d.status = d.status ? 1 : 0
    d.caseid = this.props.caseDetail.id
    d.address_type = '线下地址'
    this.$post('/api/xapc/deliveraddress', d)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.getTableData()
        } else {
          message.warning(res.message)
        }
      }).catch(() => hide())
  }

  // 更新地址请求
  updateRequest (d) {
    const hide = message.loading('更新地址中', 120)
    const id = d.id
    d.status = d.status ? 1 : 0
    d.caseid = this.props.caseDetail.id
    delete d.id
    this.$put(`/api/xapc/deliveraddress/${id}`, d)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.getTableData()
        } else {
          message.warning(res.message)
        }
      }).catch(() => hide())
  }

  // 删除地址请求
  delRequest (id) {
    const hide = message.loading('删除地址中', 120)
    this.$delete(`/api/xapc/deliveraddress/${id}`)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.getTableData()
        } else {
          message.warning(res.message)
        }
      }).catch(() => hide())
  }

  delConfirm (d) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `您确定要删除收件人为 ${d.contract} 的地址吗？`,
      onOk: () => {
        this.delRequest(d.id)
      }
    })
  }

  finishDetail (d) {
    this.setState({
      modelVisible: false
    })
    if (d.id) {
      this.updateRequest(d)
    } else {
      this.addRequest(d)
    }
  }

  componentDidMount () {
    this.getArbitrators()
    this.getDictionary()
    this.getTableData()
  }

  // 渲染人员列表
  renderPersonList (title, list) {
    if (!list.length) {
      return null
    }
    return (
      <div className={style['person-line']}>
        <div className={style['person-line__title']}>{title}：</div>
        <div className={style['person-line__tags']}>
          {list.map(li => {
            const cls = [style['person-tag']]
            if (li.id === this.state.currentId) {
              cls.push(style.active)
            }
            return (
              <div className={cls.join(' ')} key={li.id} onClick={() => this.setState({ currentId: li.id })}>{li.name}</div>
            )
          })}
        </div>
      </div>
    )
  }

  render () {
    return (
      <div>
        <Detail caseDetail={this.props.caseDetail} visible={this.state.modelVisible} data={this.state.modelData} hide={() => this.setState({ modelVisible: false, modelData: null })} onFinish={d => this.finishDetail(d)} dictionaries={this.state.dictionaries} arbitrators={this.state.arbitrators} />
        <Table size='small' loading={this.state.loading} dataSource={this.state.dataSource} columns={getColumns.call(this)} pagination={false} onChange={v => this.tableChange(v)} />
        <div className={style['add-button']}>
          <Button type='dashed' disabled={!this.props.editable} block onClick={() => this.setState({ modelVisible: true, modelData: { status: 1 } })}>+ 添加地址</Button>
        </div>
      </div>
    )
  }
}

ServiceAddress.propTypes = {
  caseDetail: PropTypes.object,
  editable: PropTypes.bool
}
ServiceAddress.defaultProps = {
  caseDetail: {},
  editable: false
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(ServiceAddress)
